<script setup>
import { onMounted, nextTick, ref, watch, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import { DocumentCopy } from "@element-plus/icons-vue";
import * as xlsx from "xlsx";
import { saveAs } from "file-saver";
import { getTideMonth, getTide24, searchAllPnt ,getAllDepartment} from "../../network/net.js";
import { formatTime } from "../../utils/cTime.js";
import iconClose from "../../assets/img/icon-关闭.png";
import { activeMenu } from "../../stores/chun.js";
import { tideValue, bmName } from '../../stores/chun.js';
import { useDraggable } from "@vueuse/core";
import iconTide from "../../assets/img/潮位站.png";
import Config from "../../components/module/Class_Map.js";


const el = ref(null)

// `style` will be a helper computed for `left: ?px; top: ?px;`
const { x, y, style } = useDraggable(el, {
  initialValue: { x: 40, y: 400 },
})
let token = sessionStorage.getItem("token");
let bm = sessionStorage.getItem("bm");
let bmInfo = sessionStorage.getItem("bmInfo");

bm = ref(bm);
bmInfo = ref(JSON.parse(bmInfo));


let tideIcon = L.icon({
  iconUrl: iconTide,
  iconSize: [35, 35],
  iconAnchor: [17, 17],
});
let tideIconSmall = L.icon({
  iconUrl: iconTide,
  iconSize: [25, 25],
  iconAnchor: [12, 12],
});

let RefTideTableDay = ref();
let RefTideTableMonth = ref();
const tideFeatureType = ref("day");

const pnts = ref([]);
const pnt = ref("");
const initPnts = () => {
  let bmData = bmInfo.value.find((item) => item.name == bmName.value);
  let bmPnts = bmData.pntIds.split(",");

  searchAllPnt(token).then((res) => {
    pnts.value = res.data.data.filter((item) => {
      return bmPnts.includes(item.pntId + "")
    })
    pnt.value = pnts.value[0].pntId

    initTideIcon();
  });
}


// const getAllDepartmentDo = ()=>{
//   getAllDepartment(token).then((res)=>{
//     console.log(res);
//   })
// }
// 初始化echarts实例
const initChart = (xAxisData, seriesData) => {
  let myChart = echarts.init(document.getElementById("tide_chart_container"));
  let option = {
    grid: { top: "40", left: "40", bottom: "40", right: "40" },
    xAxis: {
      type: "category",
      data: xAxisData,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: seriesData,
        type: "line",
        smooth: true,
        markLine: {
          data: [
            {
              yAxis: tideValue.value,
              name: "Avg",
              lineStyle: { color: "#FF0000", width: 1 }, // 样式： 线型、颜色、线宽}] type: 'solid',
            },
          ],
        },
      },
    ],
  };
  myChart.setOption(option);
};
const onChangeTideType = (value) => {
  // 潮要素类型发生变化
  if (value == "month") {
  } else if (value == "day") {
  }
};

const tableTideData = ref([]);
let arr1 = [];
let timeArr1 = [];
let valueArr1 = [];

const getChDate = (date) => {
  // 返回格式07月01日 16时
  let month = date.slice(5, 7);
  let day = date.slice(8, 10);
  let hour = date.slice(11, 13);
  return month + "月" + day + "日 " + hour + "时";
};

const tableTideMonthData = ref([]);
const getData = (pntId) => {
  if (pntId == '') return;
  tableTideData.value = [];
  timeArr1 = [];
  valueArr1 = [];



  getTide24(token, { departmentName: bmName.value, pntId }).then((res) => {
    tableTideData.value = res.data.data.map((item) => {
      return {
        forecastTime: getChDate(formatTime(item.time)),
        tide: Math.round(item.tideValue * 100),
      };
    });
    res.data.data.forEach((item, index) => {
      timeArr1.push(getChDate(formatTime(item.time)));
      valueArr1.push(Math.round(item.tideValue * 100));
    });
    nextTick(() => {
      initChart(timeArr1, valueArr1);
    });
  });

  getTideMonth(token, { departmentName: bmName.value, pntId }).then((res) => {
    let monthData = res.data.data;
    tableTideMonthData.value = [];

    // 根据dataTime从小到大排序
    monthData?.sort((a, b) => {
      return new Date(a.dataTime) - new Date(b.dataTime);
    });
    let tempArr = [];
    let num = 0;
    // 当前日期
    let startDate = formatTime(new Date()).slice(0, 7) + "-01";
    // 获取当前月份的天数
    let days = new Date(
      new Date().getFullYear(),
      new Date().getMonth() + 1,
      0
    ).getDate();
    for (let i = 0; i < days; i++) {
      let date = addDays(startDate, i);
      let data = monthData.filter((item) => item.dataTime.slice(0, 10) == date);
      let highIndexArr = [];
      let lowIndexArr = [];
      data.forEach((item, idx) => {
        if (item.varName == "TIDEUP") {
          highIndexArr.push(idx);
        } else {
          lowIndexArr.push(idx);
        }
      });
      // 根据高潮低潮高潮低潮穿插排序一个新数组 缺潮就插入null
      let tableDataArr = [];
      for (let i = 0; i < 2; i++) {
        if (highIndexArr[i] != undefined) {
          tableDataArr.push(data[highIndexArr[i]]);
        } else {
          tableDataArr.push(null);
        }
        if (lowIndexArr[i] != undefined) {
          tableDataArr.push(data[lowIndexArr[i]]);
        } else {
          tableDataArr.push(null);
        }
      }

      for (let i = 0; i < 2; i++) {
        tempArr.push({
          date: date.slice(5, 10),
          timeHigh: tableDataArr[i * 2]
            ? tableDataArr[i * 2].dataTime.slice(11, 16)
            : "**:**",
          tideHigh: tableDataArr[i * 2] ? tableDataArr[i * 2].power : "***",
          timeLow: tableDataArr[i * 2 + 1]
            ? tableDataArr[i * 2 + 1].dataTime.slice(11, 16)
            : "**:**",
          tideLow: tableDataArr[i * 2 + 1]
            ? tableDataArr[i * 2 + 1].power
            : "***",
        });
      }
    }


    for (let i = 0; i < tempArr.length / 2; i++) {
      tableTideMonthData.value.push({
        datetime: tempArr[i * 2].date,
        tidetime1H: tempArr[i * 2].timeHigh,
        tide1H: tempArr[i * 2].tideHigh,
        tidetime2H: tempArr[i * 2 + 1].timeHigh,
        tide2H: tempArr[i * 2 + 1].tideHigh,
        tidetime1L: tempArr[i * 2].timeLow,
        tide1L: tempArr[i * 2].tideLow,
        tidetime2L: tempArr[i * 2 + 1].timeLow,
        tide2L: tempArr[i * 2 + 1].tideLow,
      });
    }

  });
};

const addDays = (date, days) => {
  let d = new Date(date);
  d.setDate(d.getDate() + days);
  // 格式为yyyy-mm-dd
  return d.toISOString().split("T")[0];
};

const getTimeStr = (value) => {
  if (value == null) {
    return "-";
  }
  return value.substring(10, value.length);
};
const getValueStr = (value) => {
  if (value == null) {
    return "-";
  }
  return value;
};
const dataOutputExcel = () => {
  if (tideFeatureType.value == "day") {
    const data = [["日期", "潮位"]];
    let arr_data = tableTideData.value;
    arr_data.forEach((item) => {
      data.push([item.forecastTime, item.tide]);
    });
    const ws = xlsx.utils.aoa_to_sheet(data); // 将数组转换为 Excel 工作表
    const wb = xlsx.utils.book_new(); // 创建一个新的工作簿
    xlsx.utils.book_append_sheet(wb, ws, "Sheet1"); // 将工作表添加到工作簿
    const wbout = xlsx.write(wb, { bookType: "xlsx", type: "array" }); // 将工作簿转换为二进制数据流
    const blob = new Blob([wbout], { type: "application/octet-stream" }); // 创建二进制 Blob 对象
    saveAs(blob, "24小时逐时潮位.xlsx"); // 下载 Excel 文件，文件名为 data.xlsx
  } else if (tideFeatureType.value == "month") {
    const data = [
      [
        "日期",
        "第一高潮时",
        "第一高潮时潮位",
        "第二高潮时",
        "第二高潮时潮位",
        "第一低潮时",
        "第一低潮时潮位",
        "第二低潮时",
        "第二低潮时潮位",
      ],
    ];
    let arr_data = tableTideMonthData.value;
    arr_data.forEach((item) => {
      data.push([
        item.datetime,
        item.tidetime1H,
        item.tide1H,
        item.tidetime2H,
        item.tide2H,
        item.tidetime1L,
        item.tide1L,
        item.tidetime2L,
        item.tide2L,
      ]);
    });
    const ws = xlsx.utils.aoa_to_sheet(data); // 将数组转换为 Excel 工作表
    const wb = xlsx.utils.book_new(); // 创建一个新的工作簿
    xlsx.utils.book_append_sheet(wb, ws, "Sheet1"); // 将工作表添加到工作簿
    const wbout = xlsx.write(wb, { bookType: "xlsx", type: "array" }); // 将工作簿转换为二进制数据流
    const blob = new Blob([wbout], { type: "application/octet-stream" }); // 创建二进制 Blob 对象
    saveAs(blob, "月高低潮.xlsx"); // 下载 Excel 文件，文件名为 data.xlsx
  }
};
onMounted(() => {
  initPnts();
  // getAllDepartmentDo();
  // nextTick(() => {
  //   getData();
  // });
});

let m1 = ref('');
let m2 = ref('');
let bmData = bmInfo.value.find((item) => item.name == bmName.value);
m1.value = bmData.rasgridBaseLevel;
m2.value = bmData.tideBaseLevel;


let tideLayers = [];
const initTideIcon = () => {
  tideLayers.forEach((item) => {
    Config.mapObj.map.removeLayer(item);
  });
  pnts.value.forEach((item) => {
    let t2 = L.marker([item.lat, item.lon], { icon: tideIconSmall })
      .on("click", () => {
        pnt.value = item.pntId;
      });
    t2.addTo(Config.mapObj.map);
    tideLayers.push(t2);
  });
}
watch(pnt, () => {
  let pntIdx = pnts.value.findIndex((item) => item.pntId == pnt.value);
  tideLayers.forEach((item, idx) => {
    if (idx == pntIdx) {
      item.setIcon(tideIcon);
    } else {
      item.setIcon(tideIconSmall);
    }
  });
  getData(pnt.value);
}, {
  immediate: true
})
// onBeforeUnmount表示组件销毁前执行的函数
onBeforeUnmount(() => {
  tideLayers.forEach((item) => {
    Config.mapObj.map.removeLayer(item);
  });
});
</script>
<template>
  <div>
    <div class="tide-panel" ref="el" :style="style">
      <!-- 标题 -->
      <div class="tide-title">
        <div style="
            width: 300px;
            position: relative;
            float: left;
            line-height: 40px;
            margin: 0 0 0 25px;
            font-weight: bold;
          ">
          定点潮位预报：
          <el-select v-model="pnt" style="width: 150px;">
            <el-option v-for="item in pnts" :key="item.pntId" :label="item.name" :value="item.pntId">
            </el-option>
          </el-select>

        </div>

        <div style="
            position: relative;
            float: left;
            line-height: 40px;
          ">
          潮要素类别：
          <el-radio-group v-model="tideFeatureType" class="ml-4" @change="onChangeTideType">
            <el-radio value="month" size="large">月高低潮(潮位基准面：{{ m1 }})
            </el-radio>
            <el-radio value="day" size="large">24小时逐时潮位(潮位基准面：{{ m2 }})
            </el-radio>
          </el-radio-group>
        </div>
        <div style="
            width: auto;
            position: relative;
            float: left;
            line-height: 40px;
            margin-left: 20px;
            display: flex;
            align-items: center;
          ">
          <el-button type="primary" :icon="DocumentCopy" @click="dataOutputExcel">
            数据导出</el-button>
        </div>
        <img :src="iconClose" alt="" style="margin-left: auto; margin-right: 10px; cursor: pointer"
          @click="activeMenu = ''" />
      </div>

      <!-- 绘制潮位曲线 -->
      <div v-show="tideFeatureType == 'day'">
        <div class="tide-chart-container" id="tide_chart_container"></div>
        <div style="
            width: calc(30% - 11px);
            position: relative;
            float: left;
            margin: 5px;
          ">
          <el-table :data="tableTideData" style="width: 100%; height: 320px" ref="RefTideTableDay">
            <el-table-column prop="forecastTime" label="预报时间" />
            <el-table-column prop="tide" label="潮(cm)">
              <template #default="scope">
                <span :style="scope.row.tide > tideValue
                  ? { color: '#FF0000' }
                  : { color: '#000' }
                  ">
                  {{ scope.row.tide }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 潮位表格 -->
      <div ref="RefTideTableMonth" v-show="tideFeatureType == 'month'" class="tide-table-container"
        style="height: auto; overflow: auto">
        <!-- 表格 -->
        <el-table :data="tableTideMonthData" style="width: 100%; height: 330px">
          <el-table-column prop="datetime" label="时间" width="120" />
          <el-table-column label="高潮(cm)">
            <el-table-column prop="tidetime1H" label="第一潮时" width="120"></el-table-column>
            <el-table-column prop="tide1H" label="第一潮时潮位" width="120">
              <template #default="scope">
                <span :style="scope.row.tide1H > tideValue
                  ? { color: '#FF0000' }
                  : { color: '#000' }
                  ">
                  {{ scope.row.tide1H }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="tidetime2H" label="第二潮时"></el-table-column>
            <el-table-column prop="tide2H" label="第二潮时潮位" width="120">
              <template #default="scope">
                <span :style="scope.row.tide2H > tideValue
                  ? { color: '#FF0000' }
                  : { color: '#000' }
                  ">
                  {{ scope.row.tide2H }}
                </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="低潮(cm)">
            <el-table-column prop="tidetime1L" label="第一潮时" width="120"></el-table-column>
            <el-table-column prop="tide1L" label="第一潮时潮位" width="120">
              <template #default="scope">
                <span :style="scope.row.tide1L > tideValue
                  ? { color: '#FF0000' }
                  : { color: '#000' }
                  ">
                  {{ scope.row.tide1L }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="tidetime2L" label="第二潮时"></el-table-column>
            <el-table-column prop="tide2L" label="第二潮时潮位" width="120">
              <template #default="scope">
                <span :style="scope.row.tide2L > tideValue
                  ? { color: '#FF0000' }
                  : { color: '#000' }
                  ">
                  {{ scope.row.tide2L }}
                </span>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<style lang="less" scope>
.tide-panel {
  z-index: 999;
  position: fixed;
  // top: -10vh;
  // left: 5vw;
  width: 1250px;
  height: auto;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  // transform: translateY(100%);

  .tide-title {
    font-size: 18px;
    background: #3678c650;
    height: 40px;
    border-radius: 5px;
    text-align: left;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .tide-chart-container {
    width: 70%;
    height: 330px;
    background: #ffffffdc;
    position: relative;
    float: left;
  }

  .tide-table-container {
    width: 100%;
    height: 90%;
    background: #dcdcdcdc;
  }
}
</style>
